import { getCampusSelector } from '@/api/campus/campus'
import { getDictionaryDataSelector } from '@/api/systemData/dictionary'
import EmailInput from '@/components/CustomEmailInput'
import OrgSelect from '@/components/Process/OrgSelect'
import request from '@/utils/request'
export default {
  components: { OrgSelect, EmailInput },
  props: [],
  data() {
    return {
      loading: false,
      btnloading: false,
      visible: false,
      isDetail: false,
      status: false,
      dataForm: {
        id: undefined,
        campusId: undefined,
        type: undefined,
        refundDeposit: undefined,
        expectedRefundAmount: undefined,
        refundAmount: undefined,
        refundDate: undefined,
        refundStatus: undefined,
        refundNotes: undefined,
        closureDate: undefined,
        closureNotes: undefined,
        isEmail: false,
        emailTo: [],
        // emailCC: [],
        attachments: []
      },
      rules: {
        campusId: [
          {
            required: true,
            message: '请输入闭校校区',
            trigger: 'change'
          }
        ],
        type: [
          {
            required: true,
            message: '请输入闭校类别',
            trigger: 'change'
          }
        ],
        refundDeposit: [
          {
            required: true,
            message: '请输入退还保证金',
            trigger: 'change'
          }
        ],
        expectedRefundAmount: [
          {
            required: true,
            message: '请输入应退金额',
            trigger: 'blur'
          },
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: '请输入正确的金额',
            trigger: 'blur'
          }
        ],
        refundAmount: [
          {
            required: true,
            message: '请输入退还金额',
            trigger: 'blur'
          },
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: '请输入正确的金额',
            trigger: 'blur'
          }
        ],
        refundDate: [
          {
            required: true,
            message: '请输入退款时间',
            trigger: 'change'
          }
        ],
        refundStatus: [
          {
            required: true,
            message: '请输入退款状态',
            trigger: 'change'
          }
        ],
        refundNotes: [
          {
            required: true,
            message: '请输入退款说明',
            trigger: 'blur'
          }
        ],
        closureDate: [
          {
            required: true,
            message: '请输入闭校时间',
            trigger: 'change'
          }
        ],
        closureNotes: [
          {
            required: true,
            message: '请输入闭校说明',
            trigger: 'blur'
          }
        ]
      },
      typeOptions: [],
      refundDepositOptions: [],
      refundStatusOptions: [],
      campusOptions: [],
      // 新增：校区选项加载状态，用于初始化期间的状态控制
      campusLoading: false
    }
  },
  computed: {},
  watch: {},
  created() {
    this.gettypeOptions()
    this.getrefundDepositOptions()
    this.getrefundStatusOptions()
    // 修改：首次进入时主动加载校区选项
    this.loadCampusOptions()
  },
  mounted() {},
  methods: {
    gettypeOptions() {
      getDictionaryDataSelector('CampusCloseType').then(res => {
        this.typeOptions = res.data.list
      })
    },
    // 替换原 getCampusSelector 方法为更健壮的加载方法
    /**
     * 加载校区下拉选项数据
     * 说明：
     * - 主动请求选择器接口，规范化返回结构为 { id: string, fullName: string }
     * - 统一将 id 转为字符串，避免数字/字符串类型不一致导致 v-model 绑定失配
     */
    async loadCampusOptions() {
      this.campusLoading = true
      try {
        const res = await getCampusSelector({ fields: ['id', 'fullName'] })
        this.campusOptions = Array.isArray(res.data) ? res.data : []
      } finally {
        this.campusLoading = false
      }
    },
    /**
     * 确保校区选项已加载
     * 使用场景：在设置 dataForm.campusId 或回填表单之前调用，避免选项未就绪导致下拉显示为原始值
     */
    async ensureCampusOptions() {
      if (!this.campusOptions || this.campusOptions.length === 0) {
        await this.loadCampusOptions()
      }
    },
    getrefundDepositOptions() {
      getDictionaryDataSelector('CampusCloseDeposit').then(res => {
        this.refundDepositOptions = res.data.list
      })
    },
    getrefundStatusOptions() {
      getDictionaryDataSelector('CampusCloseRefundStatus').then(res => {
        this.refundStatusOptions = res.data.list
      })
    },
    hanlderChangStatus() {
      if (this.dataForm.refundStatus == '1' || this.dataForm.refundStatus == '4') {
        this.status = false
      } else {
        this.status = true
      }
    },
    goBack() {
      this.$emit('refresh')
    },
    /**
     * 初始化表单（支持编辑/查看/闭校）
     * 流程：
     * 1. 先确保校区选项加载完成（避免选项缺失导致只显示 campusId 原始值）
     * 2. 统一将 campusId 转为字符串类型，确保与选项的 id 严格匹配
     * 3. 根据是否有 id 决定是否拉取详情数据
     */
    async init(row, isDetail, type) {
      this.loading = true
      this.visible = true
      this.isDetail = isDetail || false
      await this.ensureCampusOptions()
      this.$nextTick(() => {
        this.$refs['elForm'].resetFields()
        this.dataForm.id = type === 'close' ? 0 : row.id
        this.dataForm.campusId = type === 'close' ? String(row.id) : undefined
        this.dataForm.expectedRefundAmount = row.deposit
        this.handleChangeCampus(row)
        if (this.dataForm.id) {
          this.fetchData()
        } else {
          this.loading = false
        }
      })
    },
    /**
     * 提取数据请求逻辑为独立方法
     * 说明：
     * - 拉取详情后先确保校区选项已加载，再回填并规范化 campusId 为字符串
     * - 避免因异步顺序或类型不一致导致 el-select 仅显示原始值而非标签
     */
    async fetchData() {
      try {
        const response = await request({
          url: `/api/campus/close/${this.dataForm.id}`,
          method: 'get'
        })
        this.dataForm = response.data
        await this.ensureCampusOptions()
        if (this.dataForm.campusId !== undefined && this.dataForm.campusId !== null) {
          this.dataForm.campusId = String(this.dataForm.campusId)
        }
        this.handleChangeCampus(response.data)
        if (!this.dataForm.attachments) this.dataForm.attachments = []
      } catch (error) {
        console.error('Failed to fetch data:', error)
        // 可以在这里添加错误处理逻辑，例如通知用户
      } finally {
        this.loading = false
      }
    },

    handleChangeCampus(campus) {
      let emailTo = ['433118678402204933', '433117269455799557', '416750280923677957', '416750736257320197', '381956723331564805', '423653212629763333', '416750360632231173', '396078644641924357', '416750479951791365', '416752342017246469', '433119597265159429', '370757840840688901', '416750440911209733', '519711074023376133', '433108138439214341', '433108138439214341']
      if (campus.company == '河北分公司') {
        emailTo.push('416749733969659141')
        emailTo.push('492107727120631045')
      } else if (campus.company == '山东分公司') {
        console.log(campus)
        emailTo.push('720164055167272197')
        emailTo.push('416748329951560965')
      } else if (campus.company == '西安分公司') {
        emailTo.push('720164338505090309')
        emailTo.push('416748748413076741')
      }
      this.onOrgChange(emailTo)
    },
    onOrgChange(data) {
      console.log(data, 1111)
      this.$nextTick(() => {
        this.dataForm.emailTo = data
        console.log(this.dataForm.emailTo, 222)
      })
    },
    dataFormSubmit() {
      this.$refs['elForm'].validate(valid => {
        if (valid) {
          this.searchTimer && clearTimeout(this.searchTimer)
          this.searchTimer = setTimeout(() => {
            this.btnloading = true
            if (!this.dataForm.id) {
              request({
                url: `/api/campus/close`,
                method: 'post',
                data: this.dataForm
              }).then(res => {
                this.$message({
                  message: res.msg,
                  type: 'success',
                  duration: 1000,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refresh', true)
                    this.btnloading = false
                  }
                })
              })
            } else {
              request({
                url: '/api/campus/close/' + this.dataForm.id,
                method: 'PUT',
                data: this.dataForm
              }).then(res => {
                this.$message({
                  message: res.msg,
                  type: 'success',
                  duration: 1000,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refresh', true)
                    this.btnloading = false
                  }
                })
              })
            }
          }, 300)
        }
      })
    }
  }
}
